package com.huaxin.hxcloud.fragment;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.platform.comapi.map.H;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.FeedBack;
import com.huaxin.common.Entity.FeedBackListDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.SDKBug;
import com.huaxin.common.view.pulltorefresh.extras.recyclerview.PullToRefreshRecyclerView;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.ReportDetailActivity;
import com.huaxin.hxcloud.dialog.DatePickerDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Administrator on 2016/9/7.
 */
public class MyReportListFragment extends BaseFragment implements View.OnClickListener {


    @BindView(R.id.more)
    TextView                  more;
    @BindView(R.id.toolbar)
    Toolbar                   toolbar;
    @BindView(R.id.pull_view)
    PullToRefreshRecyclerView pullView;
    private List      datas   = new ArrayList<>();
    private MyAdapter adapter = new MyAdapter();
    private RecyclerView listView;
    Calendar         calendar = Calendar.getInstance();
    Date             tempDate = new Date();
    SimpleDateFormat format   = new SimpleDateFormat("yyyy/MM");
    private PopupWindow popupWindow;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_my_report_list;
    }

    @Override
    public int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void requestData() {
        calendar.setTime(new Date());
        ApiRequestData(LOADING, calendar.get(Calendar.YEAR), calendar.get
                (Calendar.MONTH) + 1);
    }

    private void ApiRequestData(int status, Integer year, Integer month) {
        updateLoadStatus(status);
        Call<FeedBackListDTO> call = HxTransmitRequestHelper.getRequestApi().siteFeedbackList(year, month);
        autoClose(call);
        call.enqueue(new Callback<FeedBackListDTO>() {
            @Override
            public void onResponse(Call<FeedBackListDTO> call, Response<FeedBackListDTO> response) {
                FeedBackListDTO feedBackListDTO = response.body();
                if (response.isSuccessful()) {
                    if (feedBackListDTO != null && feedBackListDTO.isSuccessful()) {
                        updateLoadStatus(LOAD_SUCCESS);
                        updateView(feedBackListDTO.getSiteFeedbackList());
                    } else {
                        updateLoadStatus(LOAD_ERROR);
                    }
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }

            }

            @Override
            public void onFailure(Call<FeedBackListDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });


    }

    private void updateView(List<FeedBack> siteFeedbackList) {
        datas.clear();
        if (siteFeedbackList != null && !siteFeedbackList.isEmpty()) {
            datas.addAll(siteFeedbackList);
        } else {
            datas.add(Constants.EMPTY_VIEW);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void initView(View view) {
        toolbar.setTitle("我的申报");
        more.setText(format.format(tempDate));
        //        more.setImageResource(R.drawable.icon_search_f);
        pullView.setLayoutVisibilityEnable(false);
        //        addHeaderAndFooterView();
        listView = pullView.getRefreshableView();
        listView.setLayoutManager(
                new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        listView.setAdapter(adapter);


    }
    //
    //    @Override
    //    protected void updateLoadStatus(int status) {
    //        if (Util.checkNull(popupWindow)) {
    //            popupWindow = new PopupWindow(new LoadingView(getContext()), -1, -1, false);
    //
    //        }
    //        switch (status) {
    //            case LOADING:
    //                popupWindow.showAsDropDown(toolbar);
    //                break;
    //            case LOAD_SUCCESS:
    //            case LOAD_ERROR:
    //            case LOAD_FAILURE:
    //                popupWindow.dismiss();
    //                break;
    //            default:
    //                break;
    //        }
    //    }

    @Override
    protected void onResumeView() {
        super.onResumeView();
        ((BaseActivity) getActivity()).setSupportActionBar(toolbar);
    }

    @OnClick({R.id.more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.more:
                DatePickerDialog picker = new DatePickerDialog(getContext(), tempDate, new
                        DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(Date date) {
                                tempDate = date;
                                more.setText(format.format(tempDate));

                                calendar.setTime(date);
                                ApiRequestData(LOADING, calendar.get(Calendar.YEAR), calendar.get
                                        (Calendar.MONTH) + 1);
                            }
                        });
                picker.show();
                break;
            default:
                break;
        }
    }


    class MyAdapter extends RecyclerView.Adapter {
        private static final int ITEM_EMPTY       = 0x00;
        private static final int ITEM_TYPE_REPORT = 0x01;


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == ITEM_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_empty_nodata_center, parent, false));
            } else if (viewType == ITEM_TYPE_REPORT) {
                return new MyViewHolder(mInflater.inflate(R.layout.item_report, parent, false));
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == ITEM_TYPE_REPORT) {
                ((MyViewHolder) holder).update(position);
            } else if (getItemViewType(position) == ITEM_EMPTY) {
                ((EmptyHolder) holder).update(position);
            }
        }

        @Override
        public int getItemViewType(int position) {
            Object data = datas.get(position);
            if (data instanceof FeedBack) {
                return ITEM_TYPE_REPORT;
            }
            return ITEM_EMPTY;
        }


        @Override
        public int getItemCount() {
            return datas == null ? 0 : datas.size();
        }

        public class EmptyHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_tip)
            TextView tvTip;
            View itemView;

            public EmptyHolder(View itemView) {
                super(itemView);
                autoClose(ButterKnife.bind(this, itemView));
                this.itemView = itemView;
                //ImageMarkUtil.setWaterMarkTextBg(itemView,getContext(),"暂无数据");
            }

            public void update(int position) {

                tvTip.setText("该月无申报记录");
            }
        }

        class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            @BindView(R.id.type_name)
            TextView  typeName;
            @BindView(R.id.state)
            TextView  state;
            @BindView(R.id.station_name)
            TextView  stationName;
            @BindView(R.id.description)
            TextView  description;
            @BindView(R.id.img)
            ImageView img;

            View itemView;
            private int position;

            public MyViewHolder(View itemView) {
                super(itemView);
                this.itemView = itemView;
                ButterKnife.bind(this, itemView);
            }

            public void update(int position) {
                this.position = position;
                if (datas.get(position) instanceof FeedBack) {
                    FeedBack data = (FeedBack) datas.get(position);
                    loadType(data.getType());
                    loadState(data.getBackState());
                    loadText(stationName, data.getStationName());
                    loadText("描述:", description, data.getDes(), "无描述信息");
                    String[] imgs = data.getImgNames();
                    if (imgs != null && imgs.length > 0) {
                        loadNetImg(img, imgs[0]);
                        img.setVisibility(View.VISIBLE);
                    } else {
                        img.setVisibility(View.GONE);
                    }
                    itemView.setOnClickListener(this);
                }
            }

            private void loadState(int backState) {
                switch (backState) {//当前状态:0未发布;1未处理;2处理中;3处理完毕
                    case 0:
                    case 1:
                        state.setText("未处理");
                        state.setTextColor(ContextCompat.getColor(getContext(), R.color
                                .state_gray));
                        state.setBackgroundResource(R.drawable.bg_state_gray);
                        //                        itemView.setBackgroundResource(R.drawable.bg_report_item_gray);
                        SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_bt_report_item_gray);
                        break;
                    case 2:
                        state.setText("处理中");
                        state.setTextColor(ContextCompat.getColor(getContext(), R.color
                                .state_orange));
                        state.setBackgroundResource(R.drawable.bg_state_orange);
                        //                        itemView.setBackgroundResource(R.drawable.bg_report_item_orange);
                        SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_bt_report_item_orange);
                        break;
                    case 3:
                        state.setText("已处理");
                        state.setTextColor(ContextCompat.getColor(getContext(), R.color
                                .state_green));
                        state.setBackgroundResource(R.drawable.bg_state_green);
                        //                        itemView.setBackgroundResource(R.drawable.bg_report_item_green);
                        SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_bt_report_item_green);
                        break;
                    default:
                        break;
                }
            }


            private void loadType(int type) {
                switch (type) {//"厂站停电", "设备故障", "其他"
                    case 0:
                        typeName.setText("厂站停电");
                        break;
                    case 1:
                        typeName.setText("设备故障");
                        break;
                    case 2:
                        typeName.setText("其他");
                        break;
                    default:
                        break;
                }
            }


            @Override
            public void onClick(View v) {
                if (datas.get(position) instanceof FeedBack) {
                    ReportDetailActivity.start(getActivity(), (FeedBack) datas.get(position));
                }
            }
        }

    }
}
